<?php
class main extends Controller 
{

	function __construct()
	{
		parent::Controller();
		$this->load->model(array('mestatus','mcompania','mmodeloservicios','mservicios','metapas','mprocesos','mresponsable'));
	}
	
	function valores_grafica($var)
	{
		$rs=$this->mcompania->LoadCompanias();
		$verde=0;
		$amarillo=0;
		$rojo=0;
		if (count($rs[0]) > 0) {
			
		foreach ($rs as $obj)
		{
			$servicio=$this->mservicios->LoadServicioById($obj->getIdServicio());
			$tiemposervicio=$servicio->getTiempoServicio();
			
			$fecharS = "2010-05-23";
			
			if ($var == 2) {
				$dias=$this->CalcularDias($fecharS,date('Y-m-d'));
			}
			else 
			{
			$dias=$this->CalcularDias($fecharS,date('Y-m-d'));
			}
			$porciento_bruto=($dias/$tiemposervicio)*100;
			$colores_array_servicio=$this->mmodeloservicios->loadModeloServicios();
			$colores_servicios=$colores_array_servicio[0];
			if (($porciento_bruto>=$colores_servicios->getVerdeModelo() and $porciento_bruto < $colores_servicios->getAmarilloModelo()) or $porciento_bruto<=0)
			{
				$verde=$verde+1;
			}
			elseif ($porciento_bruto >=$colores_servicios->getAmarilloModelo() and $porciento_bruto < $colores_servicios->getRojoModelo()) 
			{
				$amarillo=$amarillo+1;
			}
			else 
			{
				$rojo=$rojo+1;
			}
		}
		$data=array($verde,$amarillo,$rojo);		
		return $data;
			
		}
	}
	
	function CalcularDias($fechapar,$fechaact)
	{
		
		$fechapar_arr=explode('-',$fechapar);
		$fechapar_mk=mktime(0,0,0,$fechapar_arr[1],$fechapar_arr[2],$fechapar_arr[0]);
		$fechapar_mk=intval($fechapar_mk);
		
		$fechaact_arr=explode('-',$fechaact);
		$fechaact_mk=mktime(0,0,0,$fechaact_arr[1],$fechaact_arr[2],$fechaact_arr[0]);
		$fechaact_mk=intval($fechaact_mk);
		
		$segundos_diferencia =$fechaact_mk-$fechapar_mk;
		$dias_diferencia = $segundos_diferencia / (60 * 60 * 24);
		return  $dias_diferencia;
	}
	
	function grafica_etapas()
	{
		$rs=$this->mcompania->LoadCompanias();
	
		if (count($rs[0]) > 0) {
		
		$etapam = $this->metapas->LoadEtapas();
		
		foreach ($etapam as $k)
		{
			$estapa[$k->GetNombre()] = 0;
		}

		foreach ($rs as $com)
		{	
			if ($proceso=$this->mprocesos->loadLastProceso($com->getIdCompania()))
			{	
		
				$etapa_obj=$this->mprocesos->loadProcesoById($proceso);
				
				$etapa=$etapa_obj->getIdEtapa();
			
				$nometapa = $this->metapas->LoadEtapaById($etapa);
				
				$estapa[$nometapa->GetNombre()] = $estapa[$nometapa->GetNombre()] + 1 ;
				
			}	
		}
		return $estapa;
		/*  echo '<pre>';
		  print_r($estapa);
		  echo '</pre>';
		  exit();*/
		
		$etapam = $this->metapas->LoadEtapas();
		
		
		
		foreach ($etapam as $i)
		{
			print_r($i);	
		}
		
	     exit();
		
		}	
		
	}
	
	function grafica_responsable()
	{
		$rs=$this->mcompania->LoadCompanias();
		$rs_responsables=$this->mresponsable->LoadResponsable();
		
		foreach ($rs_responsables as $k)
		{
			$cantida = $this->mcompania->LoadCompanyCantidad('IdResponsable',$k->getIdEstatus());
			
			
		}
		
		$data=array();
		
		if (count($rs[0])> 0) {

			foreach ($rs_responsables as $res)
		    { 
		      $c =0 ;
			  $responsable=$res->getNombre();
			  $repom = $this->mcompania->LoadCompaniasByIdResponsable($res->getIdEstatus());
			  if (count($repom[0]) > 0) {
			  	$c=count($repom);
			  }
			  $data[$responsable]=$c;
		     }
		    return $data;

		}
	
	}
	
 	function detruir()
    {
           	$this->session->unset_userdata('inicio');
           	$this->session->unset_userdata('fin');
           	redirect('main');
    }
	
	function grafica_estatus()
	{
		$rs=$this->mcompania->LoadCompanias();
		$inicio = 0;
	
		$estado = $this->mestatus->LoadEstatus();
		foreach ($estado as $estu)
		{
			$array[$estu->getIdEstatus()][]=1;
		}
		
		if (count($rs[0]) > 0) {
			
		
		foreach ($rs as $com)
		{
			if ($proceso=$this->mprocesos->loadLastProceso($com->getIdCompania()))
			{
				$estatus_obj=$this->mprocesos->loadProcesoById($proceso);
				$estatu=$estatus_obj->getIdEstatus();
				$estado = $this->mestatus->LoadEstatusById($estatu);
				$array[$estado->getIdEstatus()][]= 1;	
			}
			else 
			{
				$inicio++;
			}
		 
			
		}
		
		$estado = $this->mestatus->LoadEstatus();
		
		foreach ($estado as $est)
		{
			if (count($array[$est->getIdEstatus()])) {
				$num = count($array[$est->getIdEstatus()])-1;
			}
		
			if ($est->getNombre() != 'Normal') {
				$manual[$est->getIdEstatus()] =$num;
			}
			else 
			{
				$manual[$est->getIdEstatus()]=$inicio;
			}
			
			
		}
		
		
		return $manual;
		
		}
		
		return 0;
		
	}
	
	function cantidar()
	{
		
	}
	
	function index()
	{
		$responsables=$this->grafica_responsable();
		//$responsables=serialize($responsables);
		$procesos=$this->mprocesos->getUltimosProcesos();
		
		if ($this->input->post('fechasysoruser') > 0) {
			$valores=$this->valores_grafica($this->input->post('fechasysoruser'));
			
		}
		else 
		   $valores=$this->valores_grafica(1);
		
		if (@strlen($_POST['solicitud']) > 1) {
			
			$fechar1 = explode('/',$_POST['solicitud']);
			$fecharx1 = $fechar1[2].'-'.$fechar1[0].'-'.$fechar1[1];
			
			$fechar2 = explode('/',$_POST['conctato']);
			$fecharx2 = $fechar2[2].'-'.$fechar2[0].'-'.$fechar2[1];
		
			$this->session->set_userdata('inicio',$fecharx1);
	        $this->session->set_userdata('fin',$fecharx2);
			
			$this->load->view('main', array('content_page' => 'dashboard_seguimiento','estatus'=>$this->tipoEstatus(),'estapa'=>$this->tipoEstapa(),'responsable'=>$this->tipoResponsable(),'color'=>$this->tipoColor($this->input->post('fechasysoruser')),'menutop'=>0));
		}
		else {

		$data=$this->grafica_etapas();
		$est=$this->grafica_estatus();
		$this->load->view('main', array('content_page' => 'dashboard_seguimiento','estatus'=>$this->tipoEstatus(),'estapa'=>$this->tipoEstapa(),'responsable'=>$this->tipoResponsable(),'color'=>$this->tipoColor($this->input->post('fechasysoruser')),'menutop'=>0));
		}
    }
    
	//natanael
	
	function carater($care)
    {
     $care = rtrim($care);
     $care = str_split($care);

      for ($i = 0;$i < count($care);$i++)
      {
	
		if ($i >= 9)
		{
		   if ($care[$i] == ']') {
		   		return  $nom;  		
		  		   	}	
		   $nom .= 	$care[$i];
		   
		   
			}
		
       }
	
    }

	function encodeDataURL($strDataURL, $addNoCacheStr=false) {
            if ($addNoCacheStr==true) {
		    if (strpos(strDataURL,"?")<>0)
			  $strDataURL .= "&FCCurrTime=" . Date("H_i_s");
		     else
			   $strDataURL .= "?FCCurrTime=" . Date("H_i_s");
             }

	        return urlencode($strDataURL);
	
             }

    function datePart($mask, $dateTimeStr) {
             @list($datePt, $timePt) = explode(" ", $dateTimeStr);
            $arDatePt = explode("-", $datePt);
            $dataStr = "";
 
    if (count($arDatePt) == 1) {
        list($year, $month, $day) = $arDatePt;
        
        switch ($mask) {
        case "m": return $month;
        case "d": return $day;
        case "y": return $year;
        }
      
        return (trim($month . "/" . $day . "/" . $year));
    }
    return $dataStr;
}

function renderChart($chartSWF, $strURL, $strXML, $chartId, $chartWidth, $chartHeight, $debugMode, $registerWithJS) {

	if ($strXML=="")
        $tempData = "//Set the dataURL of the chart\n\t\tchart_$chartId.setDataURL(\"$strURL\")";
    else
        $tempData = "//Provide entire XML data using dataXML method\n\t\tchart_$chartId.setDataXML(\"$strXML\")";


    $chartIdDiv = $chartId . "Div";
    $ndebugMode = $this->boolToNum($debugMode);
    $nregisterWithJS = $this->boolToNum($registerWithJS);

$render_chart = <<<RENDERCHART

	<!-- START Script Block for Chart $chartId -->
	<div id="$chartIdDiv" align="center">
		Chart.
	</div>
	<script type="text/javascript">	
		//Instantiate the Chart	
		var chart_$chartId = new FusionCharts("$chartSWF", "$chartId", "$chartWidth", "$chartHeight", "$ndebugMode", "$nregisterWithJS");
		$tempData
		//Finally, render the chart.
		chart_$chartId.render("$chartIdDiv");
	</script>	
	<!-- END Script Block for Chart $chartId -->
RENDERCHART;

  return $render_chart;
}


function renderChartHTML($chartSWF, $strURL, $strXML, $chartId, $chartWidth, $chartHeight, $debugMode) {
  
    $strFlashVars = "&chartWidth=" . $chartWidth . "&chartHeight=" . $chartHeight . "&debugMode=" . $this->boolToNum($debugMode);
    if ($strXML=="")
     
        $strFlashVars .= "&dataURL=" . $strURL;
    else
     
        $strFlashVars .= "&dataXML=" . $strXML;

$HTML_chart = <<<HTMLCHART
	<!-- START Code Block for Chart $chartId -->
	<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="$chartWidth" height="$chartHeight" id="$chartId">
		<param name="allowScriptAccess" value="always" />
		<param name="movie" value="$chartSWF"/>		
		<param name="FlashVars" value="$strFlashVars" />
		<param name="quality" value="high" />
		<embed src="$chartSWF" FlashVars="$strFlashVars" quality="high" width="$chartWidth" height="$chartHeight" name="$chartId" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
	</object>
	<!-- END Code Block for Chart $chartId -->
HTMLCHART;

  return $HTML_chart;
}


function boolToNum($bVal) {
    return (($bVal==true) ? 1 : 0);
}



function tipoEstatus()
{
     $estatus = $this->mestatus->LoadEstatus();
     
    $strXML = "";
    $strXML = "<chart caption = 'Servicios Por Estatus' bgColor='#ffffff' baseFontSize='10' showValues='1' xAxisName='' >";
	
     
     foreach ($estatus as $es)
     {
     	 $strXML .= "<set label = '".$es->getNombre()."' value ='".$this->mcompania->LoadCompanyCantidad('idStatu',$es->getIdEstatus())."' />";
     }

	
$strXML .= "</chart>";

return $this->renderChartHTML(base_url()."public/swf_charts/Pie3D.swf", "",$strXML, "maestro", 362, 260, false);
	
}


function tipoEstapa()
{
    $var = $this->grafica_etapas();
	$strXML = "";
    $strXML = "<chart caption = 'Servicios Por Etapa' bgColor='#ffffff' baseFontSize='10' showValues='1' xAxisName='' >";
	
        	$etapam = $this->metapas->LoadEtapas();
        	
        	foreach ($etapam as $k)
        	{
        		$strXML .= "<set label = '".$k->GetNombre()."' value ='".$var[$k->GetNombre()]."' />";
        	}
	   
	     
		
	
$strXML .= "</chart>";

return $this->renderChartHTML(base_url()."public/swf_charts/Pie3D.swf", "",$strXML, "maestro", 362, 260, false);
	
}









function tipoResponsable()
{
    
    $rs_responsables=$this->mresponsable->LoadResponsable();
    
    
	$strXML = "";
    $strXML = "<chart caption = 'Servicios Por Reponsable' bgColor='#ffffff' baseFontSize='10' showValues='1' xAxisName='' >";
	         
       
		
		foreach ($rs_responsables as $k)
		{
			 $cantida = $this->mcompania->LoadCompanyCantidad('IdResponsable',$k->getIdEstatus());
			 
			 $responsables = $k->getNombre();
			 
			 $correccion = preg_replace('/[[:punct:]]/', ' ', $responsables);
			 
			 $strXML .= "<set label = '".$correccion."' value ='".$cantida."' />"; 
		}
    
      
$strXML .= "</chart>";

return $this->renderChartHTML(base_url()."public/swf_charts/Pie3D.swf", "",$strXML, "maestro", 362, 260, false);
	
}






function tipoColor($var2)
{
	$var[0] = 30;
	$var[1] = 10;
    $var[2] = 20;
	$strXML = "";
    $strXML = "<chart caption = 'Servicios Por Color' bgColor='#ffffff' baseFontSize='10' showValues='1' xAxisName='2' >";
	
             $strXML .= "<set label = 'Rojo' value ='".$var[2]."' />";
			 $strXML .= "<set label = 'Amarillo' value ='".$var[1]."' />";
			 $strXML .= "<set label = 'Verde' value ='".$var[0]."' />";
			 $strXML .= "<set label = '' value ='' />";
	          
		
	     
		
	
$strXML .= "</chart>";

return $this->renderChartHTML(base_url()."public/swf_charts/Pie3D.swf", "",$strXML, "maestro", 362, 260, false);
	
}


}